package com.huashi.dealer.modular.business.cart.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.Cart;
import com.huashi.dealer.commonEntity.CartGoodsSnapshot;
import com.huashi.dealer.commonEntity.Goods;
import com.huashi.dealer.commonEntity.GoodsSku;
import com.huashi.dealer.core.exception.CommonException;
import com.huashi.dealer.core.exception.ServiceException;
import com.huashi.dealer.core.util.SaTokenUtil;
import com.huashi.dealer.modular.business.cart.param.CartRequestParam;
import com.huashi.dealer.modular.business.cart.param.CartResponseParam;
import com.huashi.dealer.modular.business.cart.service.CartService;
import com.huashi.dealer.modular.business.cart.service.CheckoutService;
import com.huashi.dealer.modular.business.cart.mapper.CartGoodsSnapshotMapper;
import com.huashi.dealer.modular.business.category.service.CategoryService;
import com.huashi.dealer.modular.business.goods.mapper.*;
import lombok.extern.slf4j.Slf4j;
import com.huashi.dealer.commonEntity.DiscountActive;
import com.huashi.dealer.commonEntity.DiscountActiveGoods;
import com.huashi.dealer.commonEntity.DiscountActiveSpec;

import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveMapper;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveGoodsMapper;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveSpecMapper;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * API购物车Service实现类
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Slf4j
@Service("apiCartServiceImpl")
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsSkuMapper goodsSkuMapper;

    @Resource
    private GoodsImageMapper goodsImageMapper;

    @Resource
    private CartGoodsSnapshotMapper cartGoodsSnapshotMapper;

    @Resource
    private CheckoutService checkoutService;

    @Resource
    private DiscountActiveMapper discountActiveMapper;

    @Resource
    private DiscountActiveGoodsMapper discountActiveGoodsMapper;

    @Resource
    private DiscountActiveSpecMapper discountActiveSpecMapper;
    @Autowired
    private CategoryService categoryService;

    @Override
    public CartResponseParam addToCart(CartRequestParam requestParam) {
        CartResponseParam responseParam = new CartResponseParam();
        
        try {
            if (requestParam.getGoodsId() == null) {
                throw new CommonException("商品ID不能为空");
            }
            if (requestParam.getGoodsNum() == null || requestParam.getGoodsNum() <= 0) {
                throw new CommonException("商品数量不能为空或小于等于0");
            }
            if (requestParam.getGoodsSkuId() == null) {
                throw new CommonException("商品SKU ID不能为空");
            }
            // 解析用户ID
            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new ServiceException(401,"token无效或已过期");
            }

            long now = System.currentTimeMillis() / 1000;
            Goods goods = goodsMapper.selectById(requestParam.getGoodsId());
            Integer isGoodsType=categoryService.getById(goods.getCategoryId()).getIsGoodsType();
            // 查询是否已有相同 (userId, isGoodsType, goodsId, goodsSkuId) 的记录（未删除）
            LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cart::getUserId, userId)
                    .eq(Cart::getIsGoodsType, isGoodsType)
                    .eq(Cart::getGoodsId, requestParam.getGoodsId())
                    .eq(Cart::getGoodsSkuId, requestParam.getGoodsSkuId())
                    .eq(Cart::getIsDelete, 0);

            Cart exist = cartMapper.selectOne(wrapper);
            if (exist != null) {
                // 累加数量
                Cart toUpdate = new Cart();
                toUpdate.setCartId(exist.getCartId());
                toUpdate.setGoodsNum((exist.getGoodsNum() == null ? 0 : exist.getGoodsNum()) + requestParam.getGoodsNum());
                toUpdate.setUpdateTime(now);
                cartMapper.updateById(toUpdate);
            } else {
                // 新增记录
                Cart toInsert = new Cart();
                toInsert.setUserId(userId);
                toInsert.setIsGoodsType(isGoodsType);
                toInsert.setGoodsId(requestParam.getGoodsId());
                toInsert.setGoodsSkuId(requestParam.getGoodsSkuId());
                toInsert.setGoodsNum(requestParam.getGoodsNum());
                toInsert.setIsDelete(0);
                toInsert.setCreateTime(now);
                toInsert.setUpdateTime(now);
                cartMapper.insert(toInsert);
                
                // 新增购物车快照
                saveCartGoodsSnapshot(toInsert.getCartId(), requestParam.getGoodsId(), requestParam.getGoodsSkuId(), now);
            }

            // 统计购物车件数（sum goods_num）
            List<Cart> userItems = cartMapper.selectList(new LambdaQueryWrapper<Cart>()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getIsGoodsType, isGoodsType)
                    .eq(Cart::getIsDelete, 0));
            int totalNum = userItems.stream()
                    .map(Cart::getGoodsNum)
                    .filter(Objects::nonNull)
                    .mapToInt(Integer::intValue)
                    .sum();
            
            responseParam.setCartTotalNum(totalNum);
            responseParam.setIsGoodsType(isGoodsType);
            responseParam.setUserId(userId);
            
        } catch (Exception e) {
            throw new CommonException("加入购物车失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    /**
     * 保存购物车商品快照
     */
    private void saveCartGoodsSnapshot(Long cartId, Long goodsId, Long goodsSkuId, long createTime) {
        try {
            // 获取商品信息
            Goods goods = goodsMapper.selectById(goodsId);
            if (goods == null) {
                return;
            }

            // 获取商品SKU信息
            GoodsSku sku = goodsSkuMapper.selectById(goodsSkuId);
            if (sku == null) {
                return;
            }

            // 获取商品图片
            List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(goodsId);
            String goodsImage = imageUrls != null && !imageUrls.isEmpty() ? imageUrls.get(0) : "";

            // 创建快照记录
            CartGoodsSnapshot snapshot = new CartGoodsSnapshot();
            snapshot.setCartId(cartId);
            snapshot.setGoodsId(goodsId);
            snapshot.setGoodsSkuId(goodsSkuId);
            snapshot.setGoodsName(goods.getGoodsName());
            snapshot.setGoodsImage(goodsImage);
            snapshot.setGoodsPrice(sku.getGoodsPrice());
            snapshot.setLinePrice(sku.getLinePrice());
            snapshot.setGoodsSpec(sku.getSpec());
            snapshot.setStockNum(sku.getStockNum());
            snapshot.setCategoryId(goods.getCategoryId());
            snapshot.setSellingPoint(goods.getSellingPoint());
            snapshot.setBarCode(goods.getBarCode());
            snapshot.setSpecType(goods.getSpecType());
            snapshot.setDeductStockType(goods.getDeductStockType());
            snapshot.setGoodsStatus(goods.getGoodsStatus());
            snapshot.setCreateTime(createTime);

            cartGoodsSnapshotMapper.insert(snapshot);

        } catch (Exception e) {
            // 快照保存失败不影响主流程，只记录日志
            log.warn("保存购物车商品快照失败，cartId: {}, goodsId: {}, error: {}", cartId, goodsId, e.getMessage());
        }
    }

    @Override
    public CartResponseParam getCartList(Integer isGoodsType) {
        CartResponseParam responseParam = new CartResponseParam();

        try {

            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new ServiceException(401,"token无效或已过期");
            }

            Integer type = isGoodsType != null ? isGoodsType : 10;

            List<Cart> cartItems = cartMapper.selectList(new LambdaQueryWrapper<Cart>()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getIsGoodsType, type)
                    .eq(Cart::getIsDelete, 0)
                    .orderByDesc(Cart::getUpdateTime)); // 按创建时间倒序，与PHP保持一致

            List<CartResponseParam.CartGoodsInfo> goodsList = new ArrayList<>();
            BigDecimal totalPrice = BigDecimal.ZERO;
            int totalNum = 0;

            for (Cart item : cartItems) {
                // 从快照表获取商品信息
                CartGoodsSnapshot snapshot = cartGoodsSnapshotMapper.selectOne(
                    new LambdaQueryWrapper<CartGoodsSnapshot>()
                        .eq(CartGoodsSnapshot::getCartId, item.getCartId())
                );

                if (snapshot == null) {
                    // 如果没有快照，跳过该商品
                    log.warn("购物车商品快照缺失，cartId: {}", item.getCartId());
                    continue;
                }

                // 验证商品是否存在且未删除
                Goods goods = goodsMapper.selectById(item.getGoodsId());
                if (goods == null || goods.getIsDelete() == 1) {
                    // 商品不存在或已删除，删除购物车记录
                    cartMapper.deleteById(item.getCartId());
                    cartGoodsSnapshotMapper.delete(new LambdaQueryWrapper<CartGoodsSnapshot>()
                        .eq(CartGoodsSnapshot::getCartId, item.getCartId()));
                    continue;
                }

                // 验证商品SKU是否存在
                GoodsSku goodsSku = goodsSkuMapper.selectById(item.getGoodsSkuId());
                if (goodsSku == null) {
                    // SKU不存在，删除购物车记录
                    cartMapper.deleteById(item.getCartId());
                    cartGoodsSnapshotMapper.delete(new LambdaQueryWrapper<CartGoodsSnapshot>()
                        .eq(CartGoodsSnapshot::getCartId, item.getCartId()));
                    continue;
                }

                CartResponseParam.CartGoodsInfo info = new CartResponseParam.CartGoodsInfo();
                info.setGoodsSku(goodsSku);
                info.setCartId(item.getCartId());
                info.setGoodsId(item.getGoodsId());
                info.setGoodsSkuId(item.getGoodsSkuId());
                info.setGoodsName(snapshot.getGoodsName());
                info.setGoodsSpec(snapshot.getGoodsSpec());
                info.setGoodsPrice(snapshot.getGoodsPrice() == null ? BigDecimal.ZERO : snapshot.getGoodsPrice());
                info.setGoodsNum(item.getGoodsNum());
                info.setLinePrice(snapshot.getLinePrice() == null ? BigDecimal.ZERO : snapshot.getLinePrice());
                info.setStockNum(snapshot.getStockNum() == null ? 0 : snapshot.getStockNum());

                // 计算商品总价
                BigDecimal goodsTotalPrice = info.getGoodsPrice().multiply(new BigDecimal(item.getGoodsNum() == null ? 0 : item.getGoodsNum()));
                info.setGoodsTotalPrice(goodsTotalPrice);
                totalPrice = totalPrice.add(goodsTotalPrice);
                totalNum += (item.getGoodsNum() == null ? 0 : item.getGoodsNum());

                // 设置商品其他信息
                info.setCategoryId(snapshot.getCategoryId());
                info.setSellingPoint(snapshot.getSellingPoint());
                info.setBarCode(snapshot.getBarCode());
                info.setSpecType(snapshot.getSpecType());
                info.setDeductStockType(snapshot.getDeductStockType());
                info.setGoodsStatus(snapshot.getGoodsStatus());
                info.setGoodsImage(snapshot.getGoodsImage());

                // 设置购物车创建时间（用于排序）
                info.setCartCreateTime(item.getCreateTime());

                // TODO: 处理优惠活动信息
                // 这里需要实现优惠活动匹配逻辑
                // info.setIsActiveGoods(0); // 0-不参与活动，1-参与活动，2-活动未满足条件
                // info.setActivePrice(BigDecimal.ZERO);
                // info.setSetNum(0);
                // info.setActiveInfo(new HashMap<>());
                // info.setActiveDiscount(new ArrayList<>());

                goodsList.add(info);
            }

            // 按购物车创建时间倒序排序（与PHP保持一致）
//            goodsList.sort((a, b) -> Long.compare(b.getCartCreateTime(), a.getCartCreateTime()));

            // 处理优惠活动匹配
            goodsList = processDiscountActive(goodsList);

            // 设置基础购物车信息
            responseParam.setGoodsList(goodsList);
            responseParam.setCartTotalNum(totalNum);
            responseParam.setCartTotalPrice(totalPrice);
            responseParam.setCartCount(goodsList.size());
            responseParam.setIsGoodsType(type);
            responseParam.setUserId(userId);

            // 调用结算服务，获取完整的结算信息（类似PHP的Checkout服务）
            responseParam = checkoutService.onCheckout(userId, goodsList);

        } catch (Exception e) {
            throw new CommonException("获取购物车列表失败：" + e.getMessage());
        }

        return responseParam;
    }

    @Override
    public void deleteCartItem(String goodsSkuId, Integer isGoodsType) {
        try {

            if (goodsSkuId == null || goodsSkuId.isEmpty()) {
                throw new CommonException("商品SKU ID不能为空");
            }
            
            // 设置默认商品类型
            if (isGoodsType == null) {
                isGoodsType = 10; // 默认普通订单
            }
            
            // 获取当前用户ID
            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new CommonException("用户未登录或登录已过期");
            }
            
            // 解析商品SKU ID，支持批量删除（多个ID用逗号分隔）
            String[] goodsSkuIdArray = goodsSkuId.split(",");
            
            for (String skuIdStr : goodsSkuIdArray) {
                skuIdStr = skuIdStr.trim();
                if (skuIdStr.isEmpty()) {
                    continue;
                }
                
                // 解析商品ID和规格ID（格式：商品ID_规格ID）
                String[] parts = skuIdStr.split("_");
                if (parts.length != 2) {
                    log.warn("商品SKU ID格式错误：{}", skuIdStr);
                    continue;
                }
                
                try {
                    Long goodsId = Long.parseLong(parts[0]);
                    Long goodsSkuIdLong = Long.parseLong(parts[1]);
                    
                    // 构建删除条件
                    LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Cart::getUserId, userId)
                               .eq(Cart::getGoodsId, goodsId)
                               .eq(Cart::getGoodsSkuId, goodsSkuIdLong)
                               .eq(Cart::getIsGoodsType, isGoodsType);

                    
                    // 执行删除操作（软删除）
//                    Cart cart = new Cart();
//                    cart.setIsDelete(1); // 标记为已删除
//                    cart.setUpdateTime(System.currentTimeMillis() / 1000);
//
//                    int updateCount = cartMapper.update(cart, queryWrapper);
                    int updateCount=cartMapper.delete(queryWrapper);
                    if (updateCount > 0) {
                        log.info("成功删除购物车商品，用户ID：{}，商品ID：{}，SKU ID：{}", userId, goodsId, goodsSkuIdLong);
                    } else {
                        log.warn("未找到要删除的购物车商品，用户ID：{}，商品ID：{}，SKU ID：{}", userId, goodsId, goodsSkuIdLong);
                    }
                    
                } catch (NumberFormatException e) {
                    log.warn("商品SKU ID格式错误，无法解析数字：{}", skuIdStr);
                }
            }
            
        } catch (Exception e) {
            log.error("删除购物车商品失败：", e);
            throw new CommonException("删除购物车商品失败：" + e.getMessage());
        }
    }

    @Override
    public void reduceCartItem(String goodsSkuId, String goodsId, Integer goodsNum, Integer isGoodsType) {
        try {
            if (goodsSkuId == null || goodsSkuId.isEmpty()) {
                throw new CommonException("商品SKU ID不能为空");
            }
            if (goodsId == null || goodsId.isEmpty()) {
                throw new CommonException("商品ID不能为空");
            }
            
            // 设置默认商品类型
            if (isGoodsType == null) {
                isGoodsType = 10; // 默认普通订单
            }
            
            // 获取当前用户ID
            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new CommonException("用户未登录或登录已过期");
            }
            
            // 解析商品ID和SKU ID
            Long goodsIdLong;
            Long goodsSkuIdLong;
            try {
                goodsIdLong = Long.parseLong(goodsId);
                goodsSkuIdLong = Long.parseLong(goodsSkuId);
            } catch (NumberFormatException e) {
                throw new CommonException("商品ID或SKU ID格式错误");
            }
            
            // 查询当前购物车商品
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cart::getUserId, userId)
                       .eq(Cart::getGoodsId, goodsIdLong)
                       .eq(Cart::getGoodsSkuId, goodsSkuIdLong)
                       .eq(Cart::getIsGoodsType, isGoodsType)
                       .eq(Cart::getIsDelete, 0); // 未删除的记录
            
            Cart existingCart = cartMapper.selectOne(queryWrapper);
            
            if (existingCart == null) {
                throw new CommonException("购物车中未找到该商品");
            }
            
            // 获取当前商品数量
            Integer currentNum = existingCart.getGoodsNum();
            if (currentNum == null || currentNum <= 0) {
                throw new CommonException("购物车商品数量异常");
            }
            
            // 设置减少数量，默认为1
            if (goodsNum == null || goodsNum <= 0) {
                goodsNum = 1;
            }
            int newNum = currentNum - goodsNum;
            
            if (newNum <= 0) {
                // 如果减少后数量小于等于0，则删除该商品（软删除）
                Cart cart = new Cart();
                cart.setIsDelete(1); // 标记为已删除
                cart.setUpdateTime(System.currentTimeMillis() / 1000);
                
                int updateCount = cartMapper.update(cart, queryWrapper);
                
                if (updateCount > 0) {
                    log.info("成功删除购物车商品（数量减少到0），用户ID：{}，商品ID：{}，SKU ID：{}", userId, goodsIdLong, goodsSkuIdLong);
                } else {
                    log.warn("删除购物车商品失败，用户ID：{}，商品ID：{}，SKU ID：{}", userId, goodsIdLong, goodsSkuIdLong);
                }
            } else {
                // 更新商品数量
                Cart cart = new Cart();
                cart.setGoodsNum(newNum);
                cart.setUpdateTime(System.currentTimeMillis() / 1000);
                
                int updateCount = cartMapper.update(cart, queryWrapper);
                
                if (updateCount > 0) {
                    log.info("成功减少购物车商品数量，用户ID：{}，商品ID：{}，SKU ID：{}，原数量：{}，新数量：{}", 
                            userId, goodsIdLong, goodsSkuIdLong, currentNum, newNum);
                } else {
                    log.warn("减少购物车商品数量失败，用户ID：{}，商品ID：{}，SKU ID：{}", userId, goodsIdLong, goodsSkuIdLong);
                }
            }
            
        } catch (Exception e) {
            log.error("减少购物车商品数量失败：", e);
            throw new CommonException("减少购物车商品数量失败：" + e.getMessage());
        }
    }

    @Override
    public void clearCart(String token, Integer isGoodsType) {
        try {
            if (token == null || token.isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }
            
            // TODO: 清空购物车
            // 这里需要注入CartMapper并删除数据库记录
            
            // 模拟清空购物车
            System.out.println("清空购物车");
            
        } catch (Exception e) {
            throw new CommonException("清空购物车失败：" + e.getMessage());
        }
    }

    @Override
    public CartResponseParam updateCartItem(CartRequestParam requestParam) {
        CartResponseParam responseParam = new CartResponseParam();
        
        try {
            if (requestParam.getToken() == null || requestParam.getToken().isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }
            if (requestParam.getGoodsId() == null) {
                throw new CommonException("商品ID不能为空");
            }
            if (requestParam.getGoodsNum() == null || requestParam.getGoodsNum() <= 0) {
                throw new CommonException("商品数量不能为空或小于等于0");
            }
            
            // TODO: 更新购物车商品数量
            // 这里需要注入CartMapper并更新数据库
            
            // 模拟更新购物车商品数量
            responseParam.setCartTotalNum(1);
            
        } catch (Exception e) {
            throw new CommonException("更新购物车商品数量失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    @Override
    public CartResponseParam getCartCount(String token, Integer isGoodsType) {
        CartResponseParam responseParam = new CartResponseParam();
        
        try {
            if (token == null || token.isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }
            
            // TODO: 获取购物车商品数量
            // 这里需要注入CartMapper并查询数据库
            
            // 模拟购物车商品数量
            responseParam.setCartCount(1);
            responseParam.setCartTotalNum(1);
            
        } catch (Exception e) {
            throw new CommonException("获取购物车商品数量失败：" + e.getMessage());
        }
        
        return responseParam;
    }
    /**
     * 处理优惠活动匹配
     * 对应PHP的discount_active方法
     * @param goodsList 商品列表
     * @return 处理后的商品列表
     */
    private List<CartResponseParam.CartGoodsInfo> processDiscountActive(List<CartResponseParam.CartGoodsInfo> goodsList) {
        try {
            if (goodsList == null || goodsList.isEmpty()) {
                return goodsList;
            }

            // 1. 获取所有优惠活动商品关联
            List<DiscountActiveGoods> activeGoodsList = discountActiveGoodsMapper.selectList(null);
            if (activeGoodsList.isEmpty()) {
                return goodsList;
            }

            // 2. 按活动ID分组优惠活动商品
            Map<Long, List<DiscountActiveGoods>> activeGoodsMap = activeGoodsList.stream()
                    .collect(Collectors.groupingBy(DiscountActiveGoods::getDiscountId));

            // 3. 获取购物车中参与活动的商品
            Map<Long, List<CartResponseParam.CartGoodsInfo>> discountGoodsMap = new HashMap<>();
            for (CartResponseParam.CartGoodsInfo goods : goodsList) {
                for (Map.Entry<Long, List<DiscountActiveGoods>> entry : activeGoodsMap.entrySet()) {
                    Long discountId = entry.getKey();
                    List<DiscountActiveGoods> goodsInDiscount = entry.getValue();
                    
                    // 检查商品是否参与该活动
                    boolean isInDiscount = goodsInDiscount.stream()
                            .anyMatch(ag -> ag.getGoodsId().equals(goods.getGoodsId()));
                    
                    if (isInDiscount) {
                        discountGoodsMap.computeIfAbsent(discountId, k -> new ArrayList<>()).add(goods);
                    }
                }
            }

            // 4. 处理每个活动的商品
            for (Map.Entry<Long, List<CartResponseParam.CartGoodsInfo>> entry : discountGoodsMap.entrySet()) {
                Long discountId = entry.getKey();
                List<CartResponseParam.CartGoodsInfo> discountGoods = entry.getValue();

                // 获取活动信息
                DiscountActive active = discountActiveMapper.selectById(discountId);
                if (active == null || active.getIsDelete() == 1 || active.getStatus() != 10) {
                    continue; // 活动不存在、已删除或未启用
                }

                // 注意：根据实际数据库表结构，yoshop_discount_active表没有时间字段
                // 如果需要时间验证，需要从其他表或配置中获取

                // 计算活动商品总数量
                int totalDiscountGoodsNum = discountGoods.stream()
                        .mapToInt(goods -> goods.getGoodsNum() == null ? 0 : goods.getGoodsNum())
                        .sum();

                // 1. 验证活动的最低购买数量
                if (active.getSetNum() != null && active.getSetNum() > 0 && totalDiscountGoodsNum < active.getSetNum()) {
                    // 未达到活动最低购买数量
                    for (CartResponseParam.CartGoodsInfo goods : discountGoods) {
                        goods.setIsActiveGoods(2); // 未满足活动最低要求
                        goods.setActivePrice(goods.getGoodsPrice()); // 使用原价
                        goods.setSetNum(active.getSetNum()); // 设置最低购买数量
                        goods.setDiscountId(discountId);
                        goods.setDiscountActiveStatus(active.getStatus());
                        goods.setNewActiveGoodsNum(totalDiscountGoodsNum);
                        goods.setActiveDiscount(active);
                        goods.setActiveInfo(active);

                        // 设置活动规格信息为最低购买数量
                        Map<String, Object> activeSpecMap = new HashMap<>();
                        activeSpecMap.put("num", active.getSetNum());
                        goods.setActiveSpec(activeSpecMap);

                        // 设置活动规格列表
                        List<DiscountActiveSpec> allSpecs = discountActiveSpecMapper.selectList(
                            new LambdaQueryWrapper<DiscountActiveSpec>()
                                .eq(DiscountActiveSpec::getDiscountId, discountId)
                        );
                        goods.setActiveDiscountSpec(allSpecs.stream()
                                .map(spec -> {
                                    Map<String, Object> specMap = new HashMap<>();
                                    specMap.put("id", spec.getId());
                                    specMap.put("discountId", spec.getDiscountId());
                                    specMap.put("num", spec.getNum());
                                    specMap.put("price", spec.getPrice());
                                    return specMap;
                                })
                                .collect(Collectors.toList()));
                    }
                    continue; // 跳过后续规格匹配，直接处理下一个活动
                }

                // 2. 获取活动规格（起订数量）- 按PHP逻辑：查询num <= 商品总数量的规格，按ID降序
                List<DiscountActiveSpec> activeSpecs = discountActiveSpecMapper.selectList(
                    new LambdaQueryWrapper<DiscountActiveSpec>()
                        .eq(DiscountActiveSpec::getDiscountId, discountId)
                        .le(DiscountActiveSpec::getNum, totalDiscountGoodsNum)  // num <= 商品总数量
                        .orderByDesc(DiscountActiveSpec::getId)  // 按ID降序，对应PHP的order("id desc")
                );

                // 为每个商品设置活动信息
                for (CartResponseParam.CartGoodsInfo goods : discountGoods) {
                    // 设置基础活动信息
                    goods.setDiscountId(discountId);
                    goods.setDiscountActiveStatus(active.getStatus());
                    goods.setNewActiveGoodsNum(totalDiscountGoodsNum);
                    goods.setActiveDiscount(active);
                    goods.setActiveInfo(active); // 设置活动基本信息

                    // 检查是否满足起订数量 - 按PHP逻辑：直接取查询结果的第一个
                    if (!activeSpecs.isEmpty()) {
                        // 直接取第一个结果（因为已经按条件过滤并按ID降序）
                        DiscountActiveSpec matchedSpec = activeSpecs.get(0);
                        // 满足起订数量，参与活动
                        goods.setIsActiveGoods(1);
                        // 按PHP逻辑：只有在特定条件下才使用活动价格，否则使用原价
                        // 这里我们简化处理，直接使用活动价格（因为这是购物车列表，不是结算）
                        goods.setActivePrice(matchedSpec.getPrice());
                        goods.setSetNum(active.getSetNum()); // 设置活动的最低购买数量
                        
                        // 设置活动规格信息
                        Map<String, Object> activeSpecMap = new HashMap<>();
                        activeSpecMap.put("num", matchedSpec.getNum());
                        goods.setActiveSpec(activeSpecMap);
                    } else {
                        // 没有找到满足条件的规格，但已达到活动最低购买数量，仍然参与活动
                        List<DiscountActiveSpec> allSpecs = discountActiveSpecMapper.selectList(
                            new LambdaQueryWrapper<DiscountActiveSpec>()
                                .eq(DiscountActiveSpec::getDiscountId, discountId)
                                .orderByAsc(DiscountActiveSpec::getNum)
                        );

                        if (!allSpecs.isEmpty()) {
                            // 有规格但数量不够，使用活动基础价格或原价
                            goods.setIsActiveGoods(1); // 已达到最低购买数量，参与活动
                            // 这里可以根据业务需求选择使用活动基础价格还是原价
                            goods.setActivePrice(active.getPrice() != null ? active.getPrice() : goods.getGoodsPrice());
                            goods.setSetNum(active.getSetNum()); // 设置活动的最低购买数量

                            // 设置活动规格信息为下一个可达成的规格
                            Map<String, Object> activeSpecMap = new HashMap<>();
                            activeSpecMap.put("num", allSpecs.get(0).getNum());
                            goods.setActiveSpec(activeSpecMap);
                        } else {
                            // 没有规格设置但已达到活动最低数量，默认参与活动
                            goods.setIsActiveGoods(1);
                            goods.setActivePrice(active.getPrice() != null ? active.getPrice() : goods.getGoodsPrice());
                            goods.setSetNum(active.getSetNum());
                            goods.setActiveSpec(new HashMap<>());
                        }
                    }

                    // 设置活动规格列表 - 按PHP逻辑：获取所有规格
                    List<DiscountActiveSpec> allSpecs = discountActiveSpecMapper.selectList(
                        new LambdaQueryWrapper<DiscountActiveSpec>()
                            .eq(DiscountActiveSpec::getDiscountId, discountId)
                    );
                    goods.setActiveDiscountSpec(allSpecs.stream()
                            .map(spec -> {
                                Map<String, Object> specMap = new HashMap<>();
                                specMap.put("id", spec.getId());
                                specMap.put("discountId", spec.getDiscountId());
                                specMap.put("num", spec.getNum());
                                specMap.put("price", spec.getPrice());
                                return specMap;
                            })
                            .collect(Collectors.toList()));
                }
            }

            // 5. 为未参与活动的商品设置默认值
            for (CartResponseParam.CartGoodsInfo goods : goodsList) {
                if (goods.getIsActiveGoods() == null) {
                    goods.setIsActiveGoods(0); // 不参与活动
                    goods.setActivePrice(goods.getGoodsPrice());
                    goods.setSetNum(0);
                    goods.setDiscountId(null);
                    goods.setDiscountActiveStatus(null);
                    goods.setNewActiveGoodsNum(0);
                    goods.setActiveDiscount(null);
                    goods.setActiveInfo(null);
                    goods.setActiveSpec(null);
                    goods.setActiveDiscountSpec(new ArrayList<>());
                }
            }

            log.info("优惠活动匹配完成，商品数量: {}", goodsList.size());
            return goodsList;

        } catch (Exception e) {
            log.error("优惠活动匹配失败", e);
            // 发生异常时，为所有商品设置默认值
            for (CartResponseParam.CartGoodsInfo goods : goodsList) {
                goods.setIsActiveGoods(0);
                goods.setActivePrice(goods.getGoodsPrice());
                goods.setSetNum(0);
                goods.setDiscountId(null);
                goods.setDiscountActiveStatus(null);
                goods.setNewActiveGoodsNum(0);
                goods.setActiveDiscount(null);
                goods.setActiveInfo(null);
                goods.setActiveSpec(null);
                goods.setActiveDiscountSpec(new ArrayList<>());
            }
            return goodsList;
        }
    }
} 